package com.jl.util;

import java.awt.Component;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * @version 2012.10.27
 * @author LuHongjun
 */
public class FileUtil {

	/**
	 * 
	 * @param clazz
	 * @return
	 */
	public static String getPath(Class<?> clazz) {
		URL url = clazz.getResource("");
		String path = "";
		try {
			path = URLDecoder.decode(url.getPath(), "UTF-8");
		} catch (UnsupportedEncodingException ex) {
		}
		return path.substring(1);
	}
	
	public static void exportToFile(String text,FileNameExtensionFilter filter,Component parent) {
		JFileChooser chooser = new JFileChooser();
		//FileNameExtensionFilter filter = new FileNameExtensionFilter("Script File", "txt","scr");
		chooser.setFileFilter(filter);
		//chooser.setCurrentDirectory(new File("C:" + File.separator));
		int res = chooser.showSaveDialog(parent);
		if (res == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			String name = file.getPath();
			
			boolean isOK = filter.accept(file);
			if(!isOK){
				name += "." + filter.getExtensions()[0];
			}
			File fileEx = new File(name);
			
			
			PrintWriter out = null;
			try {
				BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(fileEx, true), 1024);
				out = new PrintWriter(bof);
				out.print(text);
				out.flush();
			} catch (FileNotFoundException ex) {
			} finally {
				if (out != null) {
					out.close();
				}
			}
		}
	}

}
